<!-- home -->
<template>
  <div class="index-container">
    <!-- <van-icon name="wap-nav" class="menu" is-link @click="showPopup" /> -->
    <span class="icon icon-cechoutigengduo menu" @click="showPopup"></span>
    <div class="loading-wrap" v-show="menuConfig[active].loading && menuConfig[active].auth">
      <!-- <van-loading size="24" vertical>Loading</van-loading> -->
    </div>
    <van-popup
      v-model="show"
      position="right"
      closeable
      :style="{ height: '100%', width: '90%' }"
      close-icon="cross"
      class="popupContent"
    >
      <site-map @navigateto="handleNavigateto"></site-map>
    </van-popup>
    <!-- v-saclick="{clickName:'clickMenuConfig',clickData:{params1: 'xxxx', title: menuConfig[active].title}}" -->
    <van-tabs class="home-tabs" @click="clickMenuConfig(menuConfig[active].title)" v-model="active">
      <van-tab v-for="(menu, index) in menuConfig" :title="menu.title" :key="index">
        <div class="report-div" v-if="menu.auth">
          <div class="filter-div" v-if="menu.showFilter">
            <DropdpwnMenu :key="keynum" @click.native="chooseCompany" :companyName="companyName"></DropdpwnMenu>
            <DateSearch :key="switchDateType" :level="switchDateType" @switchPeriod="switchPeriod"></DateSearch>
          </div>
          <iframe
            :id="`iframe_${index}`"
            :src="iframes[index]"
            frameborder="0"
            border="0"
            marginwidth="0"
            marginheight="0"
            scrolling="no"
            allowtransparency="true"
            style="background-color: transparent"
            :class="{ inner: menu.showFilter }"
            @load="iframeLoaded"
          ></iframe>
        </div>
        <no-data
          v-else
          :noAuth="menu.building"
          :desc="menu.building ? '暂无数据权限' : '驾驶舱正在逐步建设中，欢迎向项目组提出宝贵需求与建议。'"
        ></no-data>
      </van-tab>
    </van-tabs>
    <indicatorUse
      :queryDescriptionvalue="queryDescriptionvalue"
      :groupid="groupid"
      :indicatorUseShow.sync="indicatorUseShow"
    ></indicatorUse>
    <companySelection
      :saveCheckedlist="saveCheckedlist"
      @checkedlist="checkedlist"
      :orgBranchAllList="orgBranchAllList"
      :companySelectionShow.sync="companySelectionShow"
    ></companySelection>
  </div>
</template>

<script>
import DropdpwnMenu from '@/components/DropdownMenu'
import DateSearch from '@/components/DateSearch'
import NoData from '@/components/NoData'
import SiteMap from './SiteMap'
import indicatorUse from '@/components/indicatorUse'
import companySelection from '@/components/companySelection'
import sensormixin from '@/mixins'
import { queryDescription, queryOrgBranchAllList } from '@/api/home'
import { getIframeAddress } from '@/utils'
import { reportAddress } from '@/config/common'
const IS_PROD = ['production', 'prod'].includes(process.env.VUE_APP_ENV)

export default {
  components: {
    DropdpwnMenu,
    DateSearch,
    SiteMap,
    NoData,
    indicatorUse,
    companySelection
  },
  data() {
    return {
      isAndroid: false,
      saveCheckedlist: [],
      companytype: '',
      companytype2drill: '',
      switchDateType: '3',
      keynum: 0,
      orgBranchAllList: [], // 机构集合
      queryDescriptionvalue: [],
      groupid: '',
      indicatorUseShow: false,
      companySelectionShow: false,
      companyName: '',
      show: false,
      active: 0,
      loading: true,
      actionShow: false,
      actionShow1: false,
      downShow: false,
      downShow1: false,
      iframes: [],
      iframes_loaded: [],
      temp: '',
      bc: null,
      datetypeConfig: { '1': 'day', '2': 'month', '3': 'year' },
      token: '',
      menuConfig: [
        { title: '预算考核', showFilter: false, auth: true, building: true, loading: true },
        { title: '个险业务', showFilter: true, auth: true, building: true, loading: true },
        { title: '个险队伍', showFilter: true, auth: true, building: true, loading: true },
        { title: '团政业务', showFilter: true, auth: false, building: false, loading: true },
        { title: '银保业务', showFilter: true, auth: false, building: false, loading: true },
        { title: '运营科技', showFilter: true, auth: false, building: false, loading: true },
        { title: '共享后援', showFilter: true, auth: false, building: false, loading: true },
        { title: '费用结构', showFilter: true, auth: false, building: false, loading: true },
        { title: '财务简报', showFilter: true, auth: false, building: false, loading: true }
      ]
    }
  },

  mixins: [sensormixin],
  created() {
    this.token = this.$route.query.token
    const queryarr = sessionStorage.getItem('queryDescriptionvalue')
    if (!queryarr) {
      this.queryDescription()
    } else {
      this.queryDescriptionvalue = JSON.parse(queryarr)
    }
    const tem = []
    for (let index = 0; index < reportAddress.length; index++) {
      let name = this.$store.getters.userInfo ? this.$store.getters.userInfo.username : ''
      if (!IS_PROD) {
        name = 'yaoxin-011'
      }
      tem.push(getIframeAddress(name, reportAddress[index] + '&datetype=3'))
    }
    this.iframes = tem
    this.iframes_loaded = [false, false, false]
    const list = localStorage.getItem('queryOrgBranchAllList')
    if (list) {
      this.orgBranchAllList = JSON.parse(list)
    } else {
      this.getlist()
    }
  },
  mounted() {
    this.$dd.ready(() => {
      const u = navigator.userAgent
      const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // 判断是否是 android终端
      this.isAndroid = isAndroid
      if (isAndroid) {
        document.addEventListener('backbutton', this.backButtonEvent, false)
      } else {
        this.$dd.biz.navigation.setLeft({
          control: true,
          text: '返回',
          onSuccess: () => {
            this.backButtonEvent()
          },
          onFail(err) {
            console.log('返回失败', err)
          }
        })
      }
    })
    // 接收跨域信息
    // window.parent.postMessage({'action': 'open', 'targetCode': 'bphlt_sanum_ma_y', topic: 'manpower', id: '', dateType: 'year'}, '*');
    /**
      topic(指标)：perf绩效 fin表示财务 manpower人力
      dateType(时间过滤)：year当前年
      id(点击目标id):点击当前目标，拿到当前目标id传递
       -- source():表示来源于哪个表(模型)  删除
      targetCode:指标值
    */
    // window.parent.postMessage({'action': 'noauth'}, '*');
    // window.parent.postMessage({'action': 'nodata'}, '*');
    // window.parent.postMessage({'action': 'tips', 'groupid': 'hxzb'}, '*');
    window.addEventListener('message', this.msgEvent)
  },
  destroyed() {
    if (this.isAndroid) {
      document.removeEventListener('backbutton', this.backButtonEvent)
    }
    window.removeEventListener('message', this.msgEvent)
  },
  methods: {
    // 钉钉返回按钮事件
    backButtonEvent(ev) {
      if (ev) {
        ev.preventDefault() // 阻止返回
      }
      if (this.$route.name === 'Home' && this.active !== 0) {
        this.switchDateType = '3'
        this.saveCheckedlist = []
        this.companyName = '全司'
        this.keynum++
        this.companytype = ''
        this.companytype2drill = ''
      }
    },
    msgEvent(e) {
      if (e.data) {
        switch (e.data.action) {
          case 'noauth':
            this.handleNoAuth()
            break
          case 'open':
            this.handleGotoDetail(e.data)
            break
          case 'tips':
            this.handleShowTips(e.data)
            break
          case 'time':
            console.log(e.data.desc, new Date().getTime())
            break
          default:
            break
        }
      }
    },
    // 返回选择的机构
    checkedlist(arr) {
      this.saveCheckedlist = arr
      if (!arr.length) {
        this.companyName = '全司'
        this.keynum++
        this.companytype = ''
        this.companytype2drill = ''
        return
      }
      // let str = ''
      const names = ['branch', 'cen_branch', 'busi_branch']
      const types = []
      const drillsnames = ['mkt_org_branch', 'mkt_org_cen_branch', 'mkt_org_busi_branch']
      const drills = []
      arr.forEach((e, i) => {
        types.push(names[i] + '=' + e.orgBranchCode)
        drills.push(drillsnames[i] + '=' + e.orgBranchCode)
      })
      this.companytype = types.join('&')
      this.companytype2drill = drills.join('&')
      this.companyName = arr[arr.length - 1].orgBranchName
      this.keynum++
    },
    async getlist() {
      const data = await queryOrgBranchAllList()
      if (data.success) {
        this.orgBranchAllList = data.value
        localStorage.setItem('queryOrgBranchAllList', JSON.stringify(data.value))
      }
    },
    chooseCompany() {
      this.companySelectionShow = true
    },
    async queryDescription() {
      const { value } = await queryDescription()
      if (value) {
        let arr = []
        value.forEach(e => {
          arr = arr.concat(e.list)
        })
        this.queryDescriptionvalue = arr
        sessionStorage.setItem('queryDescriptionvalue', JSON.stringify(arr))
      }
    },
    showPopup() {
      this.show = true
    },
    sendInfo(params) {
      var sonIframe = document.getElementById(`iframe_${this.active}`)
      // 自动定位功能，{ action: 'scrollto', target: 'zb_nbql' }
      // const t = { action: 'scrollto', target: 'zb_nbql' }
      sonIframe.contentWindow.postMessage(params, '*')
    },
    handleNoAuth() {
      this.$set(
        this.menuConfig,
        this.active,
        Object.assign(this.menuConfig[this.active], { auth: false, loading: false })
      )
    },
    /** 打开下钻页面 */
    handleGotoDetail(data) {
      console.log('>>>>>topic handleGotoDetail:', this.companytype2drill)
      const q = `topic=${data.topic}&dateType=${this.datetypeConfig[data.dateType] || 'year'}&id=${
        data.id
      }&targetCode=${data.targetCode}&date=${data.date}&${this.companytype2drill}&companyName=${this.companyName}`
      if (this.$isDD) {
        this.$dd.ready(() => {
          this.$dd.biz.util.openLink({
            url: location.origin + '/detail?dd_nav_bgcolor=FF292E3A&showmenu=false&' + q
          })
        })
      } else {
        this.$router.push(`/detail?${q}`)
      }
    },
    /** TODO 展示指标含义的提示信息 */
    handleShowTips({ action, groupid }) {
      if (action === 'tips') {
        this.indicatorUseShow = true
        this.groupid = groupid
      }
    },
    iframeLoaded() {
      this.iframes_loaded[this.active] = true

      this.$set(this.menuConfig, this.active, Object.assign(this.menuConfig[this.active], { loading: false }))
      this.$nextTick(() => {
        if (this.bc) {
          setTimeout(() => {
            this.sendInfo(this.bcparams)
            this.bc = null
            this.bcparams = null
          }, 2000)
        }
      })
    },
    handleNavigateto(index, id) {
      this.show = false
      this.active = index
      if (this.iframes_loaded[index]) {
        this.$nextTick(() => {
          this.sendInfo({ action: 'scrollto', target: id })
        })
      } else {
        this.bc = true
        this.bcparams = { action: 'scrollto', target: id }
      }
    },
    switchPeriod(type) {
      this.switchDateType = type
    },
    setIframesActive(nr) {
      let name = this.$store.getters.userInfo ? this.$store.getters.userInfo.username : ''
      if (!IS_PROD) {
        name = 'yaoxin-011'
      }
      const nr2 = getIframeAddress(name, nr)
      this.$set(this.iframes, this.active, nr2)
    }
  },
  watch: {
    iframeDateCompanytype(a) {
      this.setIframesActive(a)
    }
  },
  computed: {
    iframeDatetype() {
      return `${reportAddress[this.active]}&datetype=${this.switchDateType}`
    },
    iframeDateCompanytype() {
      if (this.companytype) {
        return this.iframeDatetype + '&' + this.companytype
      } else {
        return this.iframeDatetype
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.index-container {
  position: relative;
  height: 100%;
  .loading-wrap {
    position: absolute;
    background-color: $main-bc;
    z-index: 100;
    width: 100%;
    height: calc(100% - 40px);
    margin-top: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .menu {
    position: absolute;
    right: 0px;
    z-index: 1;
    padding: 10px;
    padding-bottom: 12px;
    font-size: 20px;
    background-color: $main-bc;
  }

  /deep/.home-tabs {
    height: 100%;
    .van-tabs__wrap {
      padding-right: 40px;
      .van-tabs__nav {
        background-color: $main-bc;
        // background: #0C144B;
        .van-tab {
          color: #a1a5b3;
          height: 100%;
          font-size: 16px;
          padding: 0 14px;
          &.van-tab--active {
            color: #fff;
            font-weight: 600;
          }
        }
        .van-tabs__line {
          background-color: $main-blue;
          width: 64px;
        }
      }
    }
    .van-tabs__content {
      background-color: $main-bc;
      height: calc(100% - 1.17333rem);
      .van-tab__pane {
        height: 100%;
        .report-div {
          position: relative;
          height: 100%;
          .filter-div {
            display: flex;
            justify-content: space-between;
            padding: 8px 16px;
            background: $main-bc;
            .dropdown-container {
              flex: 1.5;
              margin-right: 20px;
            }
            .DateSearchList {
              flex: 1;
              // padding-left: 10px;
            }
          }
          iframe {
            width: 100%;
            height: 100%;
            border-image-width: 0;
            &.inner {
              height: calc(100% - 46px);
            }
          }
        }
      }
    }
  }
}

// /deep/.popupContent {
//   width: 100%;
//   height: 100vh;
//   background-color: $blue2;
// }
</style>
